import type { GenericFileInfo } from "@common/spider-types.ts";
import { getText } from "../util/http-utils.ts";
import * as cheerio from "cheerio";

function getPlatform() {
  switch (process.platform) {
    case "darwin":
      return "macos";
    case "linux":
      return "linux";
    case "win32":
      return "windows";
  }

  return undefined;
}

function getArch() {
  switch (process.arch) {
    case "arm":
      return ["arm"];
    case "arm64":
      return ["arm", "arm64"];
    case "ia32":
      return ["x86"];
    case "x64":
      return ["x86", "x86-64"];
  }
  return [];
}

export async function getGolangDownloadList(prefix: string): Promise<GenericFileInfo[]> {
  const resp = await getText(`${prefix}/dl/`);
  // console.log(resp.data);
  const $ = cheerio.load(resp.data);

  const platform = getPlatform();
  const supportedArch = getArch();
  const fileList: GenericFileInfo[] = [];

  // 获取稳定版本和测试版
  const versionBlocks = $(".Downloads > [id^=go]");
  versionBlocks.each((_, el) => {
    const $this = $(el);
    let versionName = $this.find(".collapsed > h3 > span").first().text();
    versionName = versionName.replace(/^go/i, "");

    // 遍历表格找出符合当前系统的版本
    $this.find(".downloadtable tbody tr").each((_, el) => {
      const $row = $(el);
      if ($row.hasClass("js-togglePorts")) {
        return;
      }

      const $td = $row.children("td");
      const kind = $td.eq(1).text().toLowerCase();
      const os = $td.eq(2).text().toLowerCase();
      const arch = $td.eq(3).text().toLowerCase();
      // 只要压缩包
      if (kind === "archive" && os === platform && supportedArch.includes(arch)) {
        const $a = $td.eq(0).find("a");
        const filename = $a.text();
        const href = $a.attr("href");
        const downloadUrl = prefix + href;
        fileList.push({
          version: versionName,
          name: filename,
          url: downloadUrl,
          type: /[a-zA-Z]/.test(versionName) ? "test" : "stable", // 版本号中包含字母的为预览版本
          bitness: arch === "x86" || arch === "arm" ? 32 : 64,
          size: $td.eq(4).text(),
        });
      }
    });
  });

  // 获取历史版本
  const historyVersionBlocks = $("#archive").find("[id^=go]");
  historyVersionBlocks.each((_, el) => {
    const $this = $(el);
    let versionName = $this.find(".collapsed > h3 > span").first().text();
    versionName = versionName.replace(/^go/i, "");
    if (/[a-zA-Z]/.test(versionName)) {
      // 去掉历史版本中的测试版
      return;
    }

    // 遍历表格找出符合当前系统的版本
    $this.find(".downloadtable tbody tr").each((_, el) => {
      const $row = $(el);
      if ($row.hasClass("js-togglePorts")) {
        return;
      }

      const $td = $row.children("td");
      const kind = $td.eq(1).text();
      const os = $td.eq(2).text()?.toLowerCase();
      const arch = $td.eq(3).text()?.toLowerCase();
      // 只要压缩包
      if (kind === "Archive" && os === platform && supportedArch.includes(arch)) {
        const $a = $td.eq(0).find("a");
        const filename = $a.text();
        const href = $a.attr("href");
        const downloadUrl = prefix + href;
        fileList.push({
          version: versionName,
          name: filename,
          url: downloadUrl,
          type: "history",
          bitness: arch === "x86" || arch === "arm" ? 32 : 64,
          size: $td.eq(4).text(),
        });
      }
    });
  });
  return fileList;
}
